<template>
  <div class="app-container v-flex">
    <filter-form :form="listQuery" :data="filterData" @search="search" @addForm="addForm" @resizeTable="resizeTable" />
    <div ref="main" class="v-flex-elastic">
      <el-table
        v-if="height>0"
        ref="multipleTable"
        v-loading="listLoading"
        :data="tableData"
        :height="height"
        tooltip-effect="dark">
        <el-table-column
          align="center"
          type="selection"
          width="50" />
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="50" />
        <el-table-column
          v-if="tableColumnCheckLists[0].ispass"
          prop="dtName"
          align="center"
          show-overflow-tooltip
          label="印章分类" />
        <el-table-column
          v-if="tableColumnCheckLists[1].ispass"
          prop="dtCode"
          align="center"
          show-overflow-tooltip
          label="印章名称" />
        <el-table-column
          prop="orderNo"
          align="center"
          show-overflow-tooltip
          label="使用人员" />
        <el-table-column
          prop="memo"
          align="center"
          show-overflow-tooltip
          label="电子印章图片" />
        <el-table-column
          prop="status"
          align="center"
          show-overflow-tooltip
          label="启动状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status===1">已启动</span>
            <span v-else>未启动</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="logo"
          align="center"
          show-overflow-tooltip
          label="编辑人员" />
        <el-table-column
          prop="createUser"
          align="center"
          show-overflow-tooltip
          label="编辑时间" />
        <el-table-column
          fixed="right"
          align="center"
          width="120"
          class-name="small-padding fixed-width">
          <template #header>
            操作
            <el-dropdown :hide-on-click="false">
              <i class="el-icon-s-operation columnSetIco" />
              <el-dropdown-menu slot="dropdown">
                <el-checkbox-group v-model="tableColumnCheck">
                  <el-dropdown-item v-for="(item,index) in checkList" :key="index"><el-checkbox :key="item" :label="item" />
                  </el-dropdown-item>
                </el-checkbox-group>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
          <template slot-scope="{row ,$index}">
            <el-button
              class="el-icon-defined"
              size="mini"
              icon="el-icon-view"
              @click="view(row)" />
            <el-button
              class="el-icon-defined"
              size="mini"
              icon="el-icon-edit"
              @click="updateForm(row,$index)" />
            <el-button
              class="el-icon-defined"
              size="mini"
              icon="el-icon-delete"
              @click="deleteData(row,$index)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-box">
      <pagination
        :total="total"
        :page.sync="listQuery.page"
        :size.sync="listQuery.size"
        @pagination="getList" />
    </div>
    <base-dialog
      class="dictionary-type-dialog"
      :visible.sync="dialog.visible"
      :title="dialog.title"
      :loading="dialog.loading"
      :disabled="dialog.disabled"
      @open="beforeOpenDialog"
      @updateData="updateData">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        :disabled="dialog.disabled"
        label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="印章分类" prop="type">
              <el-input
                v-if="dialogStatus == 'update'"
                v-model="temp.type"
                disabled />
              <el-input v-model="temp.type" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="印章名称"
              prop="name">
              <el-input
                v-if="dialogStatus == 'update'"
                v-model="temp.name"
                disabled />
              <el-input v-else v-model="temp.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="status">
              <el-radio-group v-model="temp.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="使用人员"
              prop="useUser">
              <el-input
                v-if="dialogStatus == 'update'"
                v-model="temp.useUser"
                disabled />
              <el-input v-else v-model="temp.useUser" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="使用部门"
              prop="useDept">
              <select-table-multiple
                value-key="name"
                label-key="date"
                table-value-key="name"
                :data="pillarList"
                :filter-form="selectTableModel.filterForm"
                :filter-data="selectTableModel.filterData"
                :default-data="pillars"
                :columns="selectTableModel.columns"
                :total="selectTableModel.total"
                :filter-fn="selectTableModel.filterFn"
                @selection-change="changePillar"
                @clear="pillarList=[]" />
              <el-input
                v-if="dialogStatus == 'update'"
                v-model="temp.useDept"
                disabled />
              <el-input v-else v-model="temp.useDept" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="电子印章"
              prop="fileName">
              <el-col :span="20">
                <el-input v-model="temp.fileName" />
              </el-col>
              <el-col :span="4">
                <el-upload
                  class="avatar-uploader"
                  action="/dfs/upload"
                  accept="image/*"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload">
                  <el-button>文件上传</el-button>
                </el-upload>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item
              label="备注"
              prop="memo">
              <el-input v-model="temp.memo" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </base-dialog>
  </div>
</template>

<script>
import { upload, user } from '@/api/sysm'
import { getList as deptListByTree } from './pillar'
import { getList, saveOrUpdate, deleteById } from '@/api/sysm/stration/company'
import { getList as deptByTree } from '@/api/dsc/sysm/organization/department'
import { companyAll } from '@/api/sysm/index'
import { tableMixin } from '@/utils/public'
export default {
  name: 'DscType',
  mixins: [tableMixin],
  data() {
    return {
      pillarList: [],
      selectTableModel: {
        filterForm: {
          page: 1,
          size: 10,
          companyIds: ''
        },
        filterData: {
          startPillar: {
            key: 'startPillar',
            type: 'input',
            placeholder: '开始支柱号'
          },
          endPillar: {
            key: 'endPillar',
            type: 'input',
            placeholder: '结束支柱号'
          }
        },
        columns: [
          { label: '支柱号', prop: 'date' },
          { label: '区间站场', prop: 'name', formatter: row => row.name ? row.name : '' },
          { label: '公里标', prop: 'address' }
        ],
        total: 0,
        filterFn: deptListByTree
      },
      pillars: [{
        date: '2016-05-02',
        name: '王小虎1',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-04',
        name: '王小虎2',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-01',
        name: '王小虎3',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-03',
        name: '王小虎4',
        address: '上海市普陀区金沙江路 1518 弄'
      }],
      height: 0, // table高度
      tableData: [], // 表格数据
      listQuery: {// 搜索条件
        keyName: '',
        page: 1,
        size: 20
      },
      filterData: {
        name: {
          key: 'name',
          type: 'input',
          title: '应用名称',
          placeholder: '请输入应用名称'
        },
        useUser: {
          key: 'useUser',
          type: 'select',
          title: '使用人员',
          options: [],
          props: {
            label: 'empName',
            value: 'id'
          }
        },
        status: {
          key: 'status',
          type: 'status',
          title: '是否启用',
          options: [
            {
              label: 1,
              value: '是'
            },
            {
              label: 0,
              value: '否'
            }
          ]
        }
      },
      platformOptions: [], // 所属平台option
      total: 0,
      textMap: {
        update: '编辑',
        view: '查看',
        create: '添加'
      },
      dialogFormVisible: false, // 弹窗开关
      dialogStatus: '', // 弹窗类型（添加、查看、编辑）
      dialog: {
        visible: false,
        title: '',
        loading: false,
        disabled: false
      },
      temp: {},
      tempForm: {// 弹窗表单
        id: null,
        dtName: '',
        dtCode: '',
        dtDec: '',
        isPub: true,
        isSystem: true,
        status: true
      },
      rowIndex: null,
      rules: {},
      rulesModel: {
        dtName: [{ required: true, message: '必填', trigger: 'blur' },
          { min: 1, message: '大于1个字符', trigger: 'blur' },
          { max: 20, message: '小于20个字符', trigger: 'blur' }],
        dtCode: [{ required: true, message: '必填', trigger: 'blur' },
          { min: 1, message: '大于1个字符', trigger: 'blur' },
          { max: 20, message: '小于20个字符', trigger: 'blur' }],
        dtDec: [{ max: 255, message: '小于255个字符', trigger: 'blur' }]
      },
      listLoading: false,
      disabled: false, // 是否禁止表单操作
      tableColumnCheck: ['印章分类', '印章名称'],
      checkList: ['印章分类', '印章名称'],
      tableColumnCheckLists: [
        { label: '印章分类', prop: 'dtName', ispass: true },
        { label: '印章名称', prop: 'dtCode', ispass: true }
      ]
    }
  },

  watch: {
    tableColumnCheck(newVal) {
      if (newVal) {
        var arr = this.checkList.filter(i => newVal.indexOf(i) < 0) // 未选中
        this.tableColumnCheckLists.map(i => {
          if (arr.indexOf(i.label) !== -1) {
            i.ispass = false
          } else {
            i.ispass = true
          }
        })
      }
    }
  },
  created() {
    this.temp = Object.assign({}, this.tempForm)
    this.getList()
    this.user()
    deptListByTree(this.selectTableModel.filterForm)
      .then(response => {
        this.pillars = response.data.records
        this.selectTableModel.total = response.data.total
      })
      .catch(_ => {})
    companyAll(this.selectTableModel.filterForm)
      .then(response => {
        this.pillars = response.data.records
        this.selectTableModel.total = response.data.total
      })
      .catch(_ => {})
  },
  methods: {
    // 选择支柱号
    changePillar(data) {
      console.log(data)
      this.pillarList = data
    },
    user() {
      user().then(response => {
        this.filterData.useUser.options = response.data.records
      })
    },
    // 图片上传
    beforeAvatarUpload(file) {
      const param = new FormData()
      param.append('file', file)
      upload(param).then(response => {
        this.temp.fileName = response.data
      })
      return false
    },
    // 查询列表
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
        for (const i of this.tableData) {
          i.isSystem = !!i.isSystem
          i.isPub = !!i.isPub
          i.status = !!i.status
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0 * 1000)
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 搜索
    search() {
      this.listQuery.page = 1
      this.getList()
    },
    // 添加
    addForm() {
      // this.disabled = false
      this.temp = Object.assign({}, this.tempForm)
      // this.dialogStatus = 'create'
      // this.dialogFormVisible = true
      this.rules = Object.assign({}, this.rulesModel)
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '添加',
        loading: false,
        disabled: false
      })
    },
    // 添加数据
    // addData() {
    //   this.validate().then(() => {
    //     this.saveOrUpdate(this.temp, 1)
    //   })
    // },
    // 查看
    view(row) {
      // this.disabled = true
      this.temp = Object.assign({}, row) // copy obj
      // this.dialogStatus = 'view'
      this.rules = {}
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '查看',
        loading: false,
        disabled: true
      })
    },
    // 编辑
    updateForm(row, $index) {
      // this.disabled = false
      this.rowIndex = $index
      this.temp = Object.assign({}, row) // copy obj
      // this.dialogStatus = 'update'
      this.rules = Object.assign({}, this.rulesModel)
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '编辑',
        loading: false,
        disabled: false
      })
    },
    // 编辑数据
    updateData() {
      this.validate().then(() => {
        this.saveOrUpdate(this.temp)
      })
    },
    // type 1 添加，2 编辑
    saveOrUpdate(params, type) {
      const param = Object.assign({}, params)
      param.status = param.status ? 1 : 0
      param.isPub = param.isPub ? 1 : 0
      param.isSystem = param.isSystem ? 1 : 0
      saveOrUpdate(param).then(response => {
        // response.data.status = !!response.data.status
        // response.data.isPub = !!response.data.isPub
        // response.data.isSystem = !!response.data.isSystem
        if (this.dialog.title === '添加') {
          this.tableData.unshift(response.data)
          this.total++
        } else {
          // this.getList()
          // Object.assign(this.tableData[this.rowIndex], response.data)
        }
        this.getList()
        this.notifiySuccess('保存成功!')
        this.dialog.visible = false
      })
    },
    beforeOpenDialog() {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 启用、停用,是否系统
    enable(row, $index) {
      this.rowIndex = $index
      this.saveOrUpdate(row, 2)
    },
    // 删除
    deleteData(row, $index) {
      this.confirmBox('确定删除?').then(() => {
        deleteById(row.id).then(response => {
          this.notifiySuccess('删除成功!')
          // this.tableData.splice($index, 1)
          // this.total--
          this.getList()
        })
      }).catch(() => {

      })
    }
  }
}
</script>
